package agency.tango.materialintro.fractions;

import agency.tango.materialintroscreen.parallax.ParallaxFraction;
import agency.tango.materialintro.ResourceTable;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.multimodalinput.event.TouchEvent;

public class FractionDemo extends ParallaxFraction {
    private float originStartX = 0;
    private float tempX = 0;

    @Override
    protected Component initView(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        if (scatter == null || container == null || intent == null) {
            return null;
        }
        Component root = scatter.parse(ResourceTable.Layout_layout_fraction_demo, container, false);
        if (root == null) {
            return null;
        }
        Component thisContainer = root.findComponentById(ResourceTable.Id_container);
        thisContainer.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                int width = thisContainer.getWidth();
                if (width <= 0) {
                    return false;
                }
                int action = touchEvent.getAction();
                if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                    originStartX = touchEvent.getPointerScreenPosition(0).getX();
                } else if (action == TouchEvent.POINT_MOVE) {
                    tempX = touchEvent.getPointerScreenPosition(0).getX();
                    float offset = (tempX - originStartX) / width;
                    setOffset(offset);
                } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                    originStartX = 0;
                    tempX = 0;
                    setOffset(0);
                } else if (action == TouchEvent.POINT_MOVE) {
                    originStartX = 0;
                    tempX = 0;
                    setOffset(0);
                }
                return true;
            }
        });
        return root;
    }

    @Override
    public Component getComponent() {
        return mRootView;
    }
}
